package com.siha_back.controller;

import com.siha_back.common.Result;
import com.siha_back.entity.dto.User;
import com.siha_back.service.UserService;
import com.siha_back.utils.JwtUtil;
import com.siha_back.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserService userService;
    //private final Map<String, Object> claims = new HashMap<>(); //存储user信息
    /**
     * 新增用户
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping("/register")
    public Result register(User user) {
        System.out.println(user);
        if(user.getPassword()!=null&&user.getPassword().length()>=6&&user.getPassword().length()<=16){
        //查询用户
        User u = userService.findByUserName(user.getEmail());
        System.out.println(u);
        if (u == null) {
            //没有占用
            //注册
            userService.register(user);
            return Result.success("注册成功");
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
        }else {
            return Result.error("参数不合法");
        }
    }
    /**
     * 用户登录
     *
     * @param email,password 实体
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@RequestParam("email") String email, @RequestParam("password")String password) {
       //根据用户名查询用户
       User loginUser = userService.findByUserName(email);
       //判断该用户是否存在
       if (loginUser == null) {
          return Result.error("用户名不存在");
       }
       if (password.equals(loginUser.getPassword())) {
         //登录成功
         Map<String,Object> claims = new HashMap<>();
         claims.put("id",loginUser.getId());
         claims.put("username",loginUser.getUsername());
         claims.put("email",loginUser.getEmail());
         claims.put("major",loginUser.getMajorId());
         String token = JwtUtil.genToken(claims);
         cacheToken(token,loginUser.getEmail(),loginUser.getUsername(),loginUser.getId(),loginUser.getMajorId());
         loginUser.setToken(token);
         return Result.success(200,"登录成功",loginUser);
     }
       return Result.error("用户密码错误");

}
    private void cacheToken(String token, String email, String username, Integer id,Integer major) {
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("id",id);
        userMap.put("username",username);
        userMap.put("email",email);
        userMap.put("major",major);
        //将数据以hash类型存入Redis
        String cacheKey = "UserToken:" + token;
        redisTemplate.opsForHash().putAll(cacheKey,userMap);
        //设置过期时间为30min
        redisTemplate.expire(cacheKey,30, TimeUnit.MINUTES);
    }


    /**
     * 用户详情
     *
     *
     * @return 查询该用户结果
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        //根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String email = (String) map.get("email");
        User user = userService.findByUserName(email);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(200,"成功",user);
    }

    /**
     * 上传简历
     *
     *
     * @return 上传结果
     */
    @PostMapping("/resumeUpload")
    public Result uploadResume(@RequestPart("file") MultipartFile file) {
        String file1=userService.uploadFile(file);
        return Result.success(200,"上传成功",null);
    }


//    @PutMapping("/update")
//    public Result update(@RequestBody User user) {
//        userService.update(user);
//        return Result.success();
//    }
//
//    @PatchMapping("/updatePwd")
//    public Result update(@RequestBody Map<String,String> params,HttpSession session){
//        String oldPwd = params.get("old_pwd");
//        String newPwd = params.get("new_pwd");
//        String rePwd = params.get("re_pwd");
//        System.out.println(oldPwd);
//        System.out.println(newPwd);
//        System.out.println(rePwd);
//        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
//            return Result.error("缺少必要的参数");
//        }
//
//        System.out.println("111111");
//        Map<String,Object> map = ThreadLocalUtil.get();
//        String username = (String) map.get("username");
//        System.out.println(username);
//        User loginUser = userService.findByUserName(username);
//        System.out.println(loginUser);
//        System.out.println(".......");
//        if (!loginUser.getPassword().equals(oldPwd)){
//            return Result.error("原密码错误");
//        }
//        if (!rePwd.equals(newPwd)){
//            return Result.error("两次密码不一样");
//        }
//        userService.updatePwd(newPwd);
//        return Result.success();
//
//    }
//

}
